package com.wenx.v3auth.controller;

import com.wenx.v3auth.service.UserAuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 用户认证控制器
 * 提供自定义用户认证端点，支持Client Credentials + 自定义认证模式
 * 
 * @author wenx
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Tag(name = "用户认证", description = "自定义用户认证相关接口")
public class UserAuthController {

    private final UserAuthService userAuthService;

    /**
     * 用户凭据验证端点
     * 该端点需要系统级访问令牌（client_credentials模式获取）
     * 
     * @param request 包含用户名和密码的请求体
     * @return 认证结果，包含用户token信息
     */
    @PostMapping("/validate")
    @Operation(summary = "验证用户凭据", description = "使用用户名和密码验证用户身份，返回用户专用的访问令牌")
    @PreAuthorize("hasAuthority('SCOPE_read') or hasAuthority('SCOPE_write')")
    public ResponseEntity<Map<String, Object>> validateUser(
            @Parameter(description = "用户认证请求", required = true)
            @RequestBody Map<String, String> request) {
        
        String username = request.get("username");
        String password = request.get("password");
        
        log.info("收到用户认证请求: username={}", username);
        
        try {
            Map<String, Object> result = userAuthService.validateAndGenerateToken(username, password);
            log.info("用户认证成功: username={}", username);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("用户认证失败: username={}, error={}", username, e.getMessage(), e);
            return ResponseEntity.ok(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        }
    }
    
    /**
     * 用户信息查询端点
     * 根据访问令牌获取用户基本信息
     * 
     * @return 用户信息
     */
    @GetMapping("/userinfo")
    @Operation(summary = "获取用户信息", description = "根据访问令牌获取当前用户的基本信息")
    @PreAuthorize("hasAuthority('SCOPE_read')")
    public ResponseEntity<Map<String, Object>> getUserInfo() {
        try {
            Map<String, Object> userInfo = userAuthService.getCurrentUserInfo();
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return ResponseEntity.ok(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        }
    }
}